package com.jbinfo.qingcaowan.base.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jbinfo.qingcaowan.base.dao.BaseTimeDao;
import com.jbinfo.qingcaowan.base.dto.BaseSignDTO;
import com.jbinfo.qingcaowan.base.dto.BaseTimeDTO;
import com.jbinfo.qingcaowan.base.dto.NoticeUserDTO;
import com.jbinfo.qingcaowan.base.dto.UserFullInfoDTO;
import com.jbinfo.qingcaowan.common.BusinessException;
import com.jbinfo.qingcaowan.common.ExceptionConstants.BusinessExceptionCode;
import com.jbinfo.qingcaowan.common.JSONResult;
import com.jbinfo.qingcaowan.exam.dto.ExamCircleDTO;
import com.jbinfo.qingcaowan.exam.service.CircleService;
import com.jbinfo.qingcaowan.security.entity.OrgInfo;
import com.jbinfo.qingcaowan.security.entity.OrgSub;
import com.jbinfo.qingcaowan.security.entity.Position;
import com.jbinfo.qingcaowan.security.entity.User;
import com.jbinfo.qingcaowan.studyManager.dao.CycleDetailDao;
import com.jbinfo.qingcaowan.studyManager.dto.CycleDetailDTO;
import com.jbinfo.qingcaowan.studyManager.entity.CycleMain;
import com.jbinfo.qingcaowan.studyManager.service.CycleMainService;
import com.jbinfo.qingcaowan.user.dao.OrgDao;
import com.jbinfo.qingcaowan.user.dao.OrgSubDao;
import com.jbinfo.qingcaowan.user.dao.PositionDao;
import com.jbinfo.qingcaowan.user.dao.UserDao;
import com.jbinfo.qingcaowan.user.dto.UserDTO;
import com.jbinfo.qingcaowan.user.service.UserService;

/**
 * 
* @ClassName: UserServiceImpl 
* @Description: TODO 用户管理service实现类
* @author ZhangLei 
* @date 2016年6月22日 上午10:23:02
 */
@Service("userFullService")
public class UserFullServiceImpl implements UserFullService {
	
	private Logger log = LoggerFactory.getLogger(UserFullServiceImpl.class);
	
	@Resource(name="baseSignService")
	private BaseSignService baseSignService;
	
	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="userDao")
	private UserDao userDao;
	
	@Resource(name="baseTimeDao")
	private BaseTimeDao baseTimeDao;
	
	@Resource(name="baseNoticeService")
	private BaseNoticeService baseNoticeService;
	
	@Resource(name="cycleMainService")
	private CycleMainService cycleMainService;
	
	@Resource(name="cycleDetailDao")
	private CycleDetailDao cycleDetailDao;
	
	@Resource(name="circleService")
	private CircleService circleService;
	
	@Resource(name="orgSubDao")
	private OrgSubDao orgSubDao;
	
	@Resource(name="positionDao")
	private PositionDao positionDao;
	
	@Resource(name = "orgDao")
	private OrgDao orgDao;

	@Override
	public Object getUserFullInfo(UserFullInfoDTO userFullInfoDTO) {
		// TODO Auto-generated method stub
		
		// 登陆验证
		
		String username = userFullInfoDTO.getUsername();
		String password = userFullInfoDTO.getPassword();
		
		JSONResult userJSON = (JSONResult) userService.checkUserAndPwd(username, password);
		UserDTO userDTO = userJSON.getResultBean();
		
		if (userDTO == null) {
			throw new BusinessException(BusinessExceptionCode.database_none_data, "不存在该用户信息!");
		}
		
		UserFullInfoDTO userFullDTO = new UserFullInfoDTO();
		userFullDTO.setUserId(userDTO.getUserId());
		userFullDTO.setOrgId(userDTO.getUserOrg());
		userFullDTO.setUserName(userDTO.getUserName());
		userFullDTO.setOrgName(userDTO.getOrgName());
		
		userFullDTO.setUserHeader(userDTO.getUserHeader());
		userFullDTO.setUserEmail(userDTO.getUserEmail());
		userFullDTO.setUserAddr(userDTO.getUserAddr());
		userFullDTO.setUserTel(userDTO.getUserTel());
		userFullDTO.setUserPost(userDTO.getUserPost());
		userFullDTO.setUserBirth(userDTO.getUserBirth());
		
		// 登陆状态
		BaseSignDTO signDTO = new BaseSignDTO();
		signDTO.setUserId(userDTO.getUserId());
		signDTO.setSignDate(new Date());
		
		JSONResult signStatusJson = (JSONResult) baseSignService.getSignStatus(signDTO);
		BaseSignDTO baseSign = signStatusJson.getResultBean();
		userFullDTO.setSignStatus(baseSign.getSignStatus());
		userFullDTO.setSignDate(baseSign.getStrSignDate());

		// 总阅读时间
		BaseTimeDTO baseTimeDTO = new BaseTimeDTO();
		baseTimeDTO.setUserId(userDTO.getUserId());
		
		Double dTlTime = baseTimeDao.selectTotalTime(baseTimeDTO);
		Integer nTotalTime = Integer.valueOf(0);
		if (dTlTime != null) {
			double dTotalTime = dTlTime.doubleValue();
			dTotalTime = Math.ceil(dTotalTime);
			int nTime = (int)dTotalTime;
			nTotalTime = Integer.valueOf(nTime);
		}
		userFullDTO.setTotalReadTime(nTotalTime);
		
		// 总阅读本数与总阅读天数 只查询当前有效学习计划中的本数与天数
		// 总阅读本数
//		Integer nTotalNum = baseTimeDao.selectTotalNum(baseTimeDTO);
//		userFullDTO.setTotalReadNum(nTotalNum);
		CycleDetailDTO cycleDetailDTO = new CycleDetailDTO();
		cycleDetailDTO.setUserId(userDTO.getUserId());
		cycleDetailDTO.setOrgId(userDTO.getUserOrg());
		
		BaseTimeDTO baseTime = cycleDetailDao.findCycleBookCnt(cycleDetailDTO);
		userFullDTO.setTotalReadNum(baseTime.getTotalReadNum());
		
		// 总阅读天数
//		BaseTimeDTO timeDTO = baseTimeDao.selectTotalDay(baseTimeDTO);
//		String strTotalReadDay = timeDTO.getTotalReadDay();
//		String[] readDay = strTotalReadDay.split(".");
//		
//		Integer nTotalReadDay = Integer.valueOf(0);
//		if (readDay.length > 0) {
//			nTotalReadDay = Integer.valueOf(readDay[0]);
//		}
		
		userFullDTO.setTotalReadDay(baseTime.getTotalReadDay());
		
		// 通知数
//		BaseNoticeDTO baseNoticeDTO = new BaseNoticeDTO();
//		baseNoticeDTO.setOrgId(userDTO.getUserOrg());
		NoticeUserDTO noticeUserDTO = new NoticeUserDTO();
		noticeUserDTO.setUserid(userDTO.getUserId());
		JSONResult noticeJSON = (JSONResult) baseNoticeService.getNoticeCnt(noticeUserDTO);
		
		Integer nNoticeCnt = Integer.valueOf(0);
		if (noticeJSON != null && noticeJSON.getResultBean() != null) {
			nNoticeCnt = Integer.valueOf(noticeJSON.getResultBean().toString());
		}
		userFullDTO.setnNoticeCnt(nNoticeCnt);
		
		// 查询当天是否存在阅读计划
		boolean bCircleExist = false;
		
		// 学习进度及书籍概论
		CycleMain cycleMain = new CycleMain();
		cycleMain.setOrgId(userDTO.getUserOrg());
		// 查询日期为当前日期
		cycleMain.setQueryDate(new Date());
		JSONResult cycleJSON = (JSONResult) cycleMainService.findCycleDetail(cycleMain);
		List<CycleDetailDTO> cycleDetailList = cycleJSON.getResultBean();
		
		CycleDetailDTO cycleDetail = new CycleDetailDTO();
		if (cycleDetailList != null && !cycleDetailList.isEmpty()) {
			cycleDetail = cycleDetailList.get(0);
			bCircleExist = true;
		}
		
		userFullDTO.setbCircleExist(bCircleExist);
		// 查询当天是否存在考试
		boolean bExamExist = false;
		ExamCircleDTO examCircleDTO = new ExamCircleDTO();
		examCircleDTO.setOrgId(userDTO.getUserOrg());
		examCircleDTO.setQueryDate(new Date());
		examCircleDTO.setUserId(userDTO.getUserId());
		List<ExamCircleDTO> examList = (List<ExamCircleDTO>) circleService.findNoExamCircleList(examCircleDTO);
		
		if (examList != null && !examList.isEmpty()) {
			bExamExist = true;
		}
		
		userFullDTO.setbExamExist(bExamExist);
		
		/*a.task_date, a.task_order, cycleDate,
	 	c.book_name, c.book_img, c.words, c.chapter, c.price, c.type, c.press */
		userFullDTO.setStrTaskDate(cycleDetail.getStrTaskDate());
		userFullDTO.setTaskOrder(cycleDetail.getTaskOrder());
		userFullDTO.setTaskTime(cycleDetail.getTaskTime());
		userFullDTO.setCycleDate(cycleDetail.getCycleDate());
		userFullDTO.setBookId(cycleDetail.getBookId());
		userFullDTO.setBookName(cycleDetail.getBookName());
		userFullDTO.setBookImg(cycleDetail.getBookImg());
		userFullDTO.setWords(cycleDetail.getWords());
		userFullDTO.setChapter(cycleDetail.getChapter());
		userFullDTO.setPrice(cycleDetail.getPrice());
		userFullDTO.setType(cycleDetail.getType());
		userFullDTO.setPress(cycleDetail.getPress());
		userFullDTO.setAuthor(cycleDetail.getAuthor());
		// 学习计划总阅读天数
		userFullDTO.setnTotalTaskDate(cycleDetail.getnTotalTaskDate());
		
		return userFullDTO;
	}
	
	public Object getIndexByWx(UserFullInfoDTO userFullInfoDTO) {
		// TODO Auto-generated method stub
		
		UserDTO userDTO = null;
		UserFullInfoDTO userFullDTO = new UserFullInfoDTO();
		String userId = "";
		
		try {
			// 根据传入的微信号 绑定openId
			String userWechatid = userFullInfoDTO.getUsername();
//			userDTO = userDao.findUserByWebChatId(userWechatid);
			String userIdIn = userFullInfoDTO.getUserId();
			
			if (userWechatid == null || userWechatid.isEmpty()) {
				// 如果不传入微信号，则取userId
				if (userIdIn != null && !userIdIn.isEmpty()) {
					userDTO = new UserDTO();
					userDTO.setUserId(userIdIn);
				}
				
			} else {
				
				userDTO = userDao.findUserByWebChatId(userWechatid);
			}
			
			userId = userDTO.getUserId();
			
			if (userDTO != null && userDTO.getUserId() != null) {
				// 根据userId 将从微信中获取的头像、openId 绑定到用户中
				UserDTO userDTOIn = new UserDTO();
				userDTOIn.setUserId(userDTO.getUserId());
				userDTOIn.setOpenId(userFullInfoDTO.getOpenId());
				userDTOIn.setUserHeader(userFullInfoDTO.getHeadimgurl());
				if (userFullInfoDTO.getSex() != null) {
					if (userFullInfoDTO.getSex().equals("2")) {
						userFullInfoDTO.setSex("0");
					}
				}
				userDTOIn.setUserSex(userFullInfoDTO.getSex());
				userService.updateUserInfoById(userDTOIn);
			}
		} catch (Exception e) {
			log.error("绑定微信失败:" + e.getMessage());
		}
		
		UserDTO userIdDTO = new UserDTO();
		userIdDTO.setUserId(userId);
//		JSONResult userJSON = (JSONResult) userService.getUserInfoById(userIdDTO);
		
		User userPut = (User) userDao.selectByPrimaryKey(userId);
//		UserDTO userDTOPut = userJSON.getResultBean();
		
		userFullDTO.setUserId(userId);
		if (userPut.getUserOrg() != null 
				&& !userPut.getUserOrg().isEmpty()) {

			userFullDTO.setOrgId(userPut.getUserOrg());
			OrgInfo orgInfo = orgDao.getById(userPut.getUserOrg());
			userFullDTO.setOrgName(orgInfo.getOrgName());
		}
//		userFullDTO.setUserId(userDTOPut.getUserId());
//		userFullDTO.setOrgId(userDTOPut.getUserOrg());
		userFullDTO.setUserName(userPut.getUserName());
//		userFullDTO.setOrgName(userDTOPut.getOrgName());
		
		// 获取组织名称
		if (userPut.getUserSubOrg() != null && !userPut.getUserSubOrg().isEmpty()) {
			OrgSub orgSub = orgSubDao.getById(userPut.getUserSubOrg());
			userFullDTO.setOrgSubName(orgSub.getSubOrgName());
		}
		
		// 获取职务名称
		if (userPut.getUserPosition() != null && !userPut.getUserPosition().isEmpty()) {
			Position position = positionDao.getById(userPut.getUserPosition());
			userFullDTO.setPositionName(position.getPositionName());
		}
		
		
		userFullDTO.setUserHeader(userPut.getUserHeader());
		userFullDTO.setUserEmail(userPut.getUserEmail());
		userFullDTO.setUserAddr(userPut.getUserAddr());
		userFullDTO.setUserTel(userPut.getUserTel());
		userFullDTO.setUserPost(userPut.getUserPost());
		userFullDTO.setUserBirth(userPut.getUserBirth());
		
		// 登陆状态
		BaseSignDTO signDTO = new BaseSignDTO();
		signDTO.setUserId(userId);
		signDTO.setSignDate(new Date());
		
		JSONResult signStatusJson = (JSONResult) baseSignService.getSignStatus(signDTO);
		BaseSignDTO baseSign = signStatusJson.getResultBean();
		userFullDTO.setSignStatus(baseSign.getSignStatus());
		userFullDTO.setSignDate(baseSign.getStrSignDate());
		
		// 总阅读时间
		BaseTimeDTO baseTimeDTO = new BaseTimeDTO();
		baseTimeDTO.setUserId(userId);
		
		Double dTlTime = baseTimeDao.selectTotalTime(baseTimeDTO);
		Integer nTotalTime = Integer.valueOf(0);
		if (dTlTime != null) {
			double dTotalTime = dTlTime.doubleValue();
			dTotalTime = Math.ceil(dTotalTime);
			int nTime = (int)dTotalTime;
			nTotalTime = Integer.valueOf(nTime);
		}
		
		userFullDTO.setTotalReadTime(nTotalTime);
		// 总阅读本数与总阅读天数 只查询当前有效学习计划中的本数与天数
		// 总阅读本数
//		Integer nTotalNum = baseTimeDao.selectTotalNum(baseTimeDTO);
//		userFullDTO.setTotalReadNum(nTotalNum);
		CycleDetailDTO cycleDetailDTO = new CycleDetailDTO();
		cycleDetailDTO.setUserId(userId);
		cycleDetailDTO.setOrgId(userDTO.getUserOrg());
		
		BaseTimeDTO baseTime = cycleDetailDao.findCycleBookCnt(cycleDetailDTO);
		userFullDTO.setTotalReadNum(baseTime.getTotalReadNum());
		
		// 总阅读天数
//		BaseTimeDTO timeDTO = baseTimeDao.selectTotalDay(baseTimeDTO);
//		String strTotalReadDay = timeDTO.getTotalReadDay();
//		String[] readDay = strTotalReadDay.split(".");
//		
//		Integer nTotalReadDay = Integer.valueOf(0);
//		if (readDay.length > 0) {
//			nTotalReadDay = Integer.valueOf(readDay[0]);
//		}
		
		userFullDTO.setTotalReadDay(baseTime.getTotalReadDay());
		
		// 通知数
//		BaseNoticeDTO baseNoticeDTO = new BaseNoticeDTO();
//		baseNoticeDTO.setOrgId(userDTO.getUserOrg());
		NoticeUserDTO noticeUserDTO = new NoticeUserDTO();
		noticeUserDTO.setUserid(userId);
		JSONResult noticeJSON = (JSONResult) baseNoticeService.getNoticeCnt(noticeUserDTO);
		
		Integer nNoticeCnt = Integer.valueOf(0);
		if (noticeJSON != null && noticeJSON.getResultBean() != null) {
			nNoticeCnt = Integer.valueOf(noticeJSON.getResultBean().toString());
		}
		userFullDTO.setnNoticeCnt(nNoticeCnt);
		
		// 当天是否存在阅读计划
		boolean bCircleExist = false;
		
		// 学习进度及书籍概论
		CycleMain cycleMain = new CycleMain();
		cycleMain.setOrgId(userPut.getUserOrg());
		// 查询日期为当前日期
		cycleMain.setQueryDate(new Date());
		JSONResult cycleJSON = (JSONResult) cycleMainService.findCycleDetail(cycleMain);
		List<CycleDetailDTO> cycleDetailList = cycleJSON.getResultBean();
		
		CycleDetailDTO cycleDetail = new CycleDetailDTO();
		if (cycleDetailList != null && !cycleDetailList.isEmpty()) {
			cycleDetail = cycleDetailList.get(0);
			bCircleExist = true;
		}
		userFullDTO.setbCircleExist(bCircleExist);
		
		// 查询当天是否存在考试
		boolean bExamExist = false;
		ExamCircleDTO examCircleDTO = new ExamCircleDTO();
		if (userPut.getUserOrg() != null && !userPut.getUserOrg().isEmpty()) {
			examCircleDTO.setOrgId(userPut.getUserOrg());
			examCircleDTO.setQueryDate(new Date());
			examCircleDTO.setUserId(userPut.getUserId());
			List<ExamCircleDTO> examList = (List<ExamCircleDTO>) circleService.findNoExamCircleList(examCircleDTO);
			
			if (examList != null && !examList.isEmpty()) {
				bExamExist = true;
			}
			
			userFullDTO.setbExamExist(bExamExist);
		}
		
		/*a.task_date, a.task_order, cycleDate,
	 	c.book_name, c.book_img, c.words, c.chapter, c.price, c.type, c.press */
		userFullDTO.setStrTaskDate(cycleDetail.getStrTaskDate());
		userFullDTO.setTaskOrder(cycleDetail.getTaskOrder());
		userFullDTO.setTaskTime(cycleDetail.getTaskTime());
		userFullDTO.setCycleDate(cycleDetail.getCycleDate());
		userFullDTO.setBookId(cycleDetail.getBookId());
		userFullDTO.setBookName(cycleDetail.getBookName());
		userFullDTO.setBookImg(cycleDetail.getBookImg());
		userFullDTO.setWords(cycleDetail.getWords());
		userFullDTO.setChapter(cycleDetail.getChapter());
		userFullDTO.setPrice(cycleDetail.getPrice());
		userFullDTO.setType(cycleDetail.getType());
		userFullDTO.setPress(cycleDetail.getPress());
		userFullDTO.setAuthor(cycleDetail.getAuthor());
		// 学习计划总阅读天数
		userFullDTO.setnTotalTaskDate(cycleDetail.getnTotalTaskDate());
		
		return userFullDTO;
	}
}
